package com.lw.leetcode.node;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**297. 二叉树的序列化与反序列化
 * @Author liw
 * @Date 2021/5/12 17:10
 * @Version 1.0
 */
public class Codec {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        aa(root, sb);
        System.out.println(sb.toString());
        return sb.substring(1);
    }

    private void aa (TreeNode node, StringBuilder sb) {
//        sb.append(",null");
        if (node == null) {
            return;
        }
        if (node.left != null) {
            aa(node.left, sb);
        } else {

        }

        sb.append(',');
        sb.append(node.val);
        aa(node.right, sb);
    }


    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null || data.isEmpty()) {
            return null;
        }
        String[] split = data.split(",");
        int length = split.length;
        if (length == 1 && "null".equals(split[0])) {
            return null;
        }

        Queue<TreeNode> a = new LinkedList<>();
        TreeNode f = new TreeNode(Integer.parseInt(split[0]));
        a.add(f);

        int i = 1;

        while (!a.isEmpty()) {
            TreeNode poll = a.poll();
            if (i > length) {
                break;
            }
            String s = split[i++];
            if (!"null".equals(s)) {
                TreeNode n = new TreeNode(Integer.parseInt(s));
                poll.left = n;
                a.add(n);
            }
            if (i > length) {
                break;
            }
            s = split[i++];
            if (!"null".equals(s)) {
                TreeNode n = new TreeNode(Integer.parseInt(s));
                poll.right = n;
                a.add(n);
            }
        }
        return f;
    }



}
